"""
Created on 2018/4/19 17:01 星期四
@author: Matt  zhuhan1401@126.com
Description: kNN进行分类
"""

import numpy as np
from sklearn.datasets.samples_generator import make_blobs
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt

def displayData(X,Y,centers):
    plt.figure(figsize=(16, 10), dpi=144)
    c = np.array(centers)
    plt.scatter(X[:, 0], X[:, 1], c=Y, s=100, cmap='cool');  # 画样本
    plt.scatter(c[:, 0], c[:, 1], s=100, marker='^', c='orange');  # 画样本
    plt.show()

#生成数据
centers=[[-2,2],[2,2],[0,4]]
X,Y=make_blobs(n_samples=60,centers=centers,random_state=0,cluster_std=0.60)# 生成60个分布在center中心样本 clusterStd为标准差
# displayData(X,Y,centers)  # 数据展示

# 模型训练
k=5
clf=KNeighborsClassifier(n_neighbors=k)
clf.fit(X,Y)

# 进行预测
XSample=[[0,2]] #预测(0,2)点
YSample=clf.predict(XSample)
neighbors=clf.kneighbors(XSample,return_distance=False) # 取出X中的索引

# 展示预测结果
c = np.array(centers)
plt.figure(figsize=(16,10),dpi=144)
plt.scatter(X[:, 0], X[:, 1],c=Y,s=100,cmap='cool')
plt.scatter(c[:,0],c[:,1],s=100,marker='^',c='k')
plt.scatter(XSample[0][0],XSample[0][1],marker='x',c='r',s=100,cmap='cool')
for i in neighbors[0]: # 连线
    plt.plot([X[i][0],XSample[0][0]],[X[i][1],XSample[0][1]],'k--',linewidth=0.6)
plt.show()





